package cn.com.sp.demo.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.sp.demo.SocketRunner;

public class SocketManager extends Thread{

	private static Logger LOG = LoggerFactory.getLogger(SocketManager.class);
	
	private Socket socket;
	
	private InputStream is = null;
	
	private String response = null;
	
	private OutputStream os = null;
	
	private PrintWriter pw = null;
	
	private String socketName = null;

	public SocketManager() {

	}

	public SocketManager(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		LOG.info("new socket connection");
		// 3、获取输入流，并读取客户端信息		
		try {
			is = socket.getInputStream();
			for(;;) {
				byte[] resp = new byte[4];
				int i = is.read(resp);
				if(i == -1){
					throw new Exception();
				}
				response = new String(resp, "utf-8");
				LOG.info("receive msg:" + response);
				Map<String,SocketManager> socketMap = SocketRunner.socketMap;
				if(!socketMap.containsKey(response)){
				socketName = response;
				socketMap.put(response, this);
				}
				// 4、获取输出流，响应客户端的请求
				os = socket.getOutputStream();
				pw = new PrintWriter(os);
				pw.write("received");
				pw.flush();
			}
		} catch (Exception e) {
			Map<String,SocketManager> socketMap = SocketRunner.socketMap;
			socketMap.remove(socketName);
			System.out.println("socket " + socketName + " closed");
			// 5、关闭资源			
			  pw.close(); 
			  try {
				os.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			} 
			  try {
				is.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			  try {
				socket.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		// serverSocket.close();
	}
	
	/**
	 * 发送消息
	 *
	 * @author tcf
	 * @date 2019年2月22日 下午1:37:43
	 * @param msg
	 */
	public void sendMsg(String msg){
		pw = new PrintWriter(os);
		pw.write(msg);
		pw.flush();
	}
	
	/**
	 * 接收消息
	 *
	 * @author tcf
	 * @date 2019年2月22日 下午1:37:52
	 * @param socket
	 */
	public void receiveMsg(String msg){

	}
	
}
